#!/usr/bin/python

from sys import argv, stdin, stderr, stdout, exit
from os import system, fork, wait, getpid
from socket import socket, timeout

# the main function translates <nodeid>.<value> using the nodes file

default = { "usr":"root","pwd":"","ip" : "0.0.0.0", "vip":"0:0:0:0:0:0/0","bssid":"0:1:1:1:1:!","router":"0:0:0:0:0:0","dn" : "nohost","power":"0" }
RUNTIME_DIR = '~/more'

def readNodes(file):
    """ Parses a nodes file.
        Empty lines or lines commented with '#' are skipped
    """
    out = {}
    for lr in file:
        if(lr[0] == "#"):
            continue
        l = lr.split()
        if(len(l) == 0):
            continue
        if(len(l) < 8):
            raise Exception("Malformed nodes file! " + lr)
        r = {}
        r["usr"] = l[0]
        r["pwd"] = l[1]
        r["ip"] = l[2]
        r["vip"] = l[3]
        r["bssid"] = l[4]
        r["router"] = l[5]
        r["dn"] = l[6]
        r["power"]=l[7]
        out[l[2]] = r

    try: file.close()
    except: pass
    return out

def writeNodes(nodes, file):
    """ dumps to a file
    """
    for r in nodes.values():
        print >> file, r["usr"],r["pwd"],r["ip"], r["vip"],r["bssid"],r["router"],r["dn"],r["power"]
    file.close()


from threading import Thread
from thread import interrupt_main
import pexpect
def forNodes(nodes, run, cmd, serial=False, debug=False):
    if(type(nodes) is dict):
        # we just need a list
        nodes = nodes.values()
    
    def forOne(n):
        ssh_newkey = 'Are you sure you want to continue connecting'
        try:
            program=run.split(" ")[0]
            if(program=="ssh"):
                c = run + '"'+cmd+'"'
            else: c= run % n
            c=c%n
            p=pexpect.spawn(c)
            i=p.expect([ssh_newkey,'password:','sftp>','100%',pexpect.EOF])
            if i==0:
                p.sendline('yes')
                i=p.expect([ssh_newkey,'password:','sftp>','100%',pexpect.EOF])
            if i==1:
                p.sendline(n['pwd'])
                i=p.expect([ssh_newkey,'password:','sftp>','100%',pexpect.EOF])
                if (i==4 and program=="ssh"): 
                    print c+'successed!\n'
                    return
            if i==2:
                print cmd
                p.sendline(cmd%n)
                i=p.expect([ssh_newkey,'password:','sftp>','100%',pexpect.EOF])
                if i==3:
                    print c+cmd%n+' successed!\n'
                    return
                else:
                    print c+cmd%n+' failed!\n'
                    return  
            elif i==4:
                print c+'failed!\n'
                return        
        except KeyboardInterrupt:
            interrupt_main()

    if(serial): 
        for n in nodes: forOne(n)
    else: 
        # create threads
        threads = []
        for n in nodes:
            threads.append(Thread(target=forOne, args=(n,)))
        for t in threads: t.start()
        for t in threads: t.join()
    return

# all this script does is it converts nodes_ids to actual nodes
# provide a nodes-like file
# then wherever it sees 1.ip it will put in the ip of node 1
# ip = ethernet IP
# mac = roofnet MAC
# dn = domain name
def main(args):
    if(len(args) < 2):
        print "Usage: %s <nodefile>" % args[0]
        return -1

    nodes = readNodes(open(argv[1]))

    for l in stdin:
        # find all int.string
        l = l.split()
        for e in l:
            es = e.split('.')
            try:
                print nodes.get(es[0], default)[es[1]],
            except:
                print e,
        print

if(__name__ == "__main__"):
    main(argv)

